//
//  GameCenterLogin.m
//  GameProject
//
//  Created by Blair Trusler on 24/11/2011.
//  Copyright (c) 2011 Blair Trusler. All rights reserved.
//

#import "GameHeader.h"

@implementation GameCenterLogin

@synthesize scoresToReport;
@synthesize achievementsToReport;


static GameCenterLogin *sharedHelper = nil;

+(GameCenterLogin *)sharedInstance{
    @synchronized ([GameCenterLogin class]){
        if (!sharedHelper){
            sharedHelper = [loadData(@"GameCenterData")retain];
            if (!sharedHelper){
                [[self alloc] initWithScoresToReport:[NSMutableArray array] achievementsToReport:[NSMutableArray array]];

            }

        }
        return sharedHelper;
    }
    return nil;
}

-(void)save{
    saveData(self,@"GameCenterData");
}


+(id)alloc{
    @synchronized ([GameCenterLogin class]){
        NSAssert(sharedHelper == nil, @"Attempted to allocate a second instance of the GameCenterLogin singelton");
        sharedHelper = [super alloc];
        return sharedHelper;
    }
    return nil;
}

//Check user iOS version to ensure game center can be enabled:
-(BOOL)isGameCenterAvailable{
    //Check for GKLocalPlayer API
	Class gcClass = (NSClassFromString(@"GKLocalPlayer"));
    
    //Check device is 4.1+
    NSString *reqVer = @"4.1";
    NSString *currentVer = [[UIDevice currentDevice]systemVersion];
    NSLog(@"User iOS Version: %@",currentVer);
    
    BOOL versionSupported = ([currentVer compare:reqVer options:NSNumericSearch]!=NSOrderedAscending);
    return (gcClass && versionSupported);
}


-(id)initWithScoresToReport:(NSMutableArray *)theScoresToReport achievementsToReport:(NSMutableArray *)theAchievementsToReport{
    if ((self=[super init])){
        NSLog(@"Game center init");
        self.scoresToReport = theScoresToReport;
        self.achievementsToReport = theAchievementsToReport; 
        
        gameCenterAvailable = [self isGameCenterAvailable];
        if (gameCenterAvailable){
            NSNotificationCenter *nc = 
            [NSNotificationCenter defaultCenter];
            [nc addObserver:self selector:@selector(authenticationChanged) name:GKPlayerAuthenticationDidChangeNotificationName object:nil];            
        }
        
    }
    return self;
}


-(void)authenticationChanged{
    dispatch_async(dispatch_get_main_queue(), ^(void){
        if ([GKLocalPlayer localPlayer].isAuthenticated && !userAuthenticated){
            NSLog(@"Player Authenticated");
            userAuthenticated = TRUE;
            
            [self resendData];
            
        }
        else if (![GKLocalPlayer localPlayer].isAuthenticated && userAuthenticated){
            NSLog(@"Player Not Authenticated");
            userAuthenticated = FALSE;
        }
    });
}


-(void)sendScore:(GKScore *)score{
    [score reportScoreWithCompletionHandler:^(NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^(void){
            if (error == NULL){
                CCLOG(@"Score sent!");
                [scoresToReport removeObject:score];
                
            }
            else{
                CCLOG(@"Score failed to send!");
            }
            
        });
    }];
}


-(void)sendAchievement:(GKAchievement *)achievement{
    [achievement reportAchievementWithCompletionHandler:^(NSError *error){
        dispatch_async(dispatch_get_main_queue(),^(void){
            if (error == NULL){
                NSLog(@"Sent achievement");
                
                //TODO: Put this back in on iMac version:
                achievement.showsCompletionBanner = YES;
                [achievementsToReport removeObject:achievement];
            }else{
                    NSLog(@"Achievement failed to send");
            }
        });
    }];
}

-(void)resendData{
    for (GKAchievement *achievement in achievementsToReport){
        [self sendAchievement:achievement];
    }
    for (GKScore *score in scoresToReport){
        [self sendScore:score];
    }
}



-(void)authenticateLocalUser{
    if (!gameCenterAvailable) return;
    
    NSLog(@"Authenticating local user...");
    if ([GKLocalPlayer localPlayer].authenticated == NO) {     
        [[GKLocalPlayer localPlayer] authenticateWithCompletionHandler:nil];        
    } else {
        NSLog(@"Already authenticated!");
    }
}




-(void)reportScore:(NSString *)identifier score:(int)rawScore{
    GKScore *score = [[[GKScore alloc]initWithCategory:identifier]autorelease];
    score.value = rawScore;
    [scoresToReport addObject:score];
    [self save];
    
    if (!gameCenterAvailable||!userAuthenticated){
        CCLOG(@"Cannot sent score to leaderboard - not logged into Game Center");
//        CCLOG(@"Score Sent");
//        [self sendScore:score];
    }
    else{
        CCLOG(@"Score Sent");
        [self sendScore:score];

    }
}

-(void)reportAchievement:(NSString *)identifier percentComplete:(double)percentComplete{
    GKAchievement *achievement = [[[GKAchievement alloc] initWithIdentifier:identifier]autorelease];
    
    achievement.percentComplete = percentComplete;
    
//    GKAchievementDescription *desc = [achievementsDescDictionary objectForKey:identifier]; //Update pull achievement description for dictionary
//    
//    [[GKAchievementHandler defaultHandler] notifyAchievement:desc];  //Display to user

    
    [achievementsToReport addObject:achievement];
    [self save];
    
    if(!gameCenterAvailable || !userAuthenticated) return;
    
    [self sendAchievement:achievement];
}



-(void)encodeWithCoder:(NSCoder *)encoder{
    [encoder encodeObject:scoresToReport forKey:@"ScoresToReport"];
    [encoder encodeObject:achievementsToReport forKey:@"AchievementsToReport"];
}

-(id)initWithCoder:(NSCoder *)decoder{
    NSMutableArray *theScoresToReport = [decoder decodeObjectForKey:@"ScoresToReport"];
    NSMutableArray *theAchievementsToReport = [decoder decodeObjectForKey:@"AchievementsToReport"];
    
    return [self initWithScoresToReport:theScoresToReport achievementsToReport:theAchievementsToReport];
    
}

@end
